"a11y-onkeydown": A React Hook for Accessible-Friendly onKeyDown Events
When building React applications, it's important to make them as accessible as possible for all users, including those who rely on keyboard navigation. However, it's easy to accidentally create "keyboard traps" where a user cannot move focus away from an interactive element or control using the keyboard alone. That's where the "a11y-onkeydown" package comes in.
This package provides a simple, reusable hook that allows you to trigger onKeyDown events only when certain keys are pressed, avoiding the need to check the key every time. This is especially useful when working with interactive elements that require keyboard event handlers.
To use the hook, simply import it from the package and pass it as the value for the onKeyDown attribute of your element. By default, the hook will trigger onKeyDown for any key except for "Shift" and "Tab", allowing keyboard users to tab up and down the tab stack. Here's an example:
import { useKeyDown } from 'a11y-onkeydown';
function MyButton({ text, handleSelect }) {
return (
<div
role="button"
tabIndex={0}
onClick={handleSelect}
onKeyDown={useKeyDown(handleSelect)}
>
{text}
</div>
);
}
In this example, the "handleSelect" function will be called when the user presses any key except for "Shift" and "Tab". However, you may want to only call onKeyDown if certain keys are pressed. In that case, you can pass an array of strings as the second argument to useKeyDown. For example, if you only want to trigger onKeyDown when the user presses "Enter", "ArrowUp", or "ArrowDown", you can do this:
import { useKeyDown } from 'a11y-onkeydown';
function MyButton({ text, handleSelect }) {
return (
<div
role="button"
tabIndex={0}
onClick={handleSelect}
onKeyDown={useKeyDown(handleSelect, ['Enter', 'ArrowUp', 'ArrowDown'])}
>
{text}
</div>
);
}
With this configuration, the "handleSelect" function will only be called when the user presses one of the specified keys.
In summary, "a11y-onkeydown" is a simple and useful package for making your React applications more accessible to keyboard users. By using this hook, you can avoid creating keyboard traps and provide a better user experience for all.